package com.psedu.base.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.psedu.base.constant.Constants;
import com.psedu.base.domain.Apply;
import com.psedu.base.domain.SemesterDept;
import com.psedu.base.domain.vo.*;
import com.psedu.base.mapper.ApplyMapper;
import com.psedu.base.mapper.SemesterDeptMapper;
import com.psedu.common.core.constant.SecurityConstants;
import com.psedu.common.core.domain.R;
import com.psedu.system.api.RemoteDeptService;
import com.psedu.system.api.RemoteUserService;
import com.psedu.system.api.domain.vo.SysSimpleDeptVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.bcel.Const;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.psedu.base.mapper.SemesterMapper;
import com.psedu.base.domain.Semester;
import com.psedu.base.service.ISemesterService;

/**
 * 学期Service业务层处理
 * 
 * @author mingyue
 * @date 2022-02-09
 */
@Slf4j
@Service
public class SemesterServiceImpl implements ISemesterService 
{
    @Autowired
    private SemesterMapper semesterMapper;

    @Autowired
    private ApplyMapper applyMapper;

    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private RemoteDeptService remoteDeptService;

    @Autowired
    private SemesterDeptMapper semesterDeptMapper;

    /**
     * 查询学期
     * 
     * @param semeId 学期主键
     * @return 学期
     */
    @Override
    public Semester selectSemesterBySemeId(Long semeId)
    {
        return semesterMapper.selectSemesterBySemeId(semeId);
    }

    /**
     * 查询学期列表
     * 
     * @param semester 学期
     * @return 学期
     */
    @Override
    public List<Semester> selectSemesterList(Semester semester)
    {
        return semesterMapper.selectSemesterList(semester);
    }

    /**
     * 新增学期
     * 
     * @param semester 学期
     * @return 结果
     */
    @Override
    public int insertSemester(Semester semester)
    {
        return semesterMapper.insert(semester);
    }

    /**
     * 修改学期
     * 
     * @param semester 学期
     * @return 结果
     */
    @Override
    public int updateSemester(Semester semester)
    {
        return semesterMapper.updateById(semester);
    }

    /**
     * 修改学期
     *
     * @param semester 学期
     * @return 结果
     */
    @Override
    public int updateSemesterStatus(Semester semester)
    {
        Integer active = semester.getActive();
        // 分党校全部关闭
        if(Constants.SEMESTER_INACTIVE == active) {
            SemesterDept semesterDept = new SemesterDept();
            semesterDept.setStarted(active);
            semesterDeptMapper.update(
                    semesterDept,
                    new LambdaQueryWrapper<SemesterDept>()
                        .eq(SemesterDept::getSemeId, semester.getSemeId())
            );
        }
        return semesterMapper.updateById(semester);
    }

    /**
     * 批量删除学期
     * 
     * @param semeIds 需要删除的学期主键
     * @return 结果
     */
    @Override
    public int deleteSemesterBySemeIds(Long[] semeIds)
    {
        return semesterMapper.deleteSemesterBySemeIds(semeIds);
    }

    /**
     * 删除学期信息
     * 
     * @param semeId 学期主键
     * @return 结果
     */
    @Override
    public int deleteSemesterBySemeId(Long semeId)
    {
        return semesterMapper.deleteSemesterBySemeId(semeId);
    }

    @Override
    public List<SimpleSelectSemesterVo> simpleSelectList() {
        LambdaQueryWrapper<Semester> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(
                        Semester::getSemeId, Semester::getSemeName
                    ).orderByDesc(Semester::getSemeId);
        return semesterMapper.selectVoList(
                queryWrapper,
                SimpleSelectSemesterVo.class
        );
    }

    @Override
    public List<SimpleSemesterVo> canSignSemester() {
        LambdaQueryWrapper<Semester> semesterQueryWrapper = new LambdaQueryWrapper<Semester>();
        semesterQueryWrapper.select(
                Semester::getSemeId, Semester::getSemeName, Semester::getActive, Semester::getStartTime, Semester::getEndTime
        );
        semesterQueryWrapper.eq(Semester::getActive, 1);
        return semesterMapper.selectVoList(semesterQueryWrapper, SimpleSemesterVo.class);
    }

    @Override
    public Integer getTrainObjectBySemesterId(Long semeId) {
        Semester semester = semesterMapper.selectById(semeId);
        if(semester == null || semester.getTrainObject() == null) {
            return -1;
        }
        return semester.getTrainObject();
    }

    @Override
    public SemeDetailVo getSemesterDetail(Long semeId) {
        SemeDetailVo semeDetailVo = new SemeDetailVo();
        // 报名数量
        Long applyCount = applyMapper.selectCount(
                new LambdaQueryWrapper<Apply>()
                        .eq(Apply::getSemeId, semeId)
        );
        semeDetailVo.setApplyCount(applyCount);

        // 已审核人数
        Long checkedCount = applyMapper.selectCount(
                new LambdaQueryWrapper<Apply>()
                        .eq(Apply::getSemeId, semeId)
                        .ne(Apply::getChecked, Constants.APPLY_WAIT)
        );
        semeDetailVo.setCheckedCount(checkedCount);

        // 已分组人数
        Long groupUserCount = applyMapper.selectCount(
                new LambdaQueryWrapper<Apply>()
                        .eq(Apply::getSemeId, semeId)
                        .ne(Apply::getGroupId, 0)
        );
        semeDetailVo.setGroupUserCount(groupUserCount);

        // 注册人数
        try {
            R<Long> registerUserCountR = remoteUserService.getPsStudentNum(SecurityConstants.INNER);
            Long registerUserCount = registerUserCountR.getData();
            semeDetailVo.setDeptRegisterCount(registerUserCount);
        } catch (Exception e) {
            log.error(e.getMessage());
            semeDetailVo.setDeptRegisterCount(-1L);
        }

        // 部门数据
        fillDeptApplyData(semeId, semeDetailVo);
        return semeDetailVo;
    }

    private void fillDeptApplyData(Long semeId, SemeDetailVo semeDetailVo) {
        List<Long> deptIds = new ArrayList<>();
        for (long deptId = Constants.MIN_COLLEGE_DEPT_ID; deptId < Constants.MAX_COLLEGE_DEPT_ID; deptId++) {
            deptIds.add(deptId);
        }
        R<List<SysSimpleDeptVo>> simpleDeptVoListR = remoteDeptService.getDeptNameByDeptId(deptIds, SecurityConstants.INNER);
        List<SysSimpleDeptVo> simpleDeptVoList = simpleDeptVoListR.getData();
        Map<Long, String> allDeptMap = simpleDeptVoList.stream().collect(
                Collectors.toMap(
                        SysSimpleDeptVo::getDeptId,
                        SysSimpleDeptVo::getDeptName
                )
        );
        List<SemesterDeptApplyCountVo> semesterDeptApplyCountVos =  applyMapper.selectSemesterDeptApplyCount(semeId);
        Map<Long, Long> deptApplyCountVoMap = semesterDeptApplyCountVos.stream().collect(
                Collectors.toMap(SemesterDeptApplyCountVo::getDeptId, SemesterDeptApplyCountVo::getCount)
        );
        SemeDetailVo.DeptApplyData deptApplyData = new SemeDetailVo.DeptApplyData();
        semeDetailVo.setDeptApplyData(deptApplyData);
        List<Long> deptApplyCountList = new ArrayList<>();
        List<String> deptNameList = new ArrayList<>();
        deptApplyData.setApplyCountList(deptApplyCountList);
        deptApplyData.setDeptNameList(deptNameList);
        for (Map.Entry<Long, String> deptNameEntry : allDeptMap.entrySet()) {
            Long deptId = deptNameEntry.getKey();
            String deptName = deptNameEntry.getValue();
            deptNameList.add(deptName);
            deptApplyCountList.add(deptApplyCountVoMap.getOrDefault(deptId, 0L));
        }
    }
}
